package io.renren.modules.app.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.annotation.LoginUser;
import io.renren.modules.app.entity.CollectVo;
import io.renren.modules.app.entity.UserVo;
import io.renren.modules.app.service.ApiCollectService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 商品收藏api
 * @author zzh
 * @email 862583291@qq.com
 * @date 2019-6-24 12:27
 */
@Api("商品收藏api")
@RestController
@RequestMapping("/app/v1/collect")
public class ApiCollectController {

    @Autowired
    private ApiCollectService apiCollectService;

    /**
     *收藏或取消收藏
     */
    @Login
    @PostMapping("/addordelete")
    public R addordelete(@LoginUser UserVo userVo,@RequestBody Map<String, Object> params){
        System.out.println(userVo.toString());
        System.out.println(params.toString());
        if(StringUtil.isNullOrEmpty(params.get("valueId"))){
            return R.error("参数不能为空");
        }
        if(StringUtil.isNullOrEmpty(params.get("typeId"))){
            return R.error("参数不能为空");
        }
        List<CollectVo> collectEntities = apiCollectService.list(
               new QueryWrapper<CollectVo>().eq("user_id",userVo.getUserId()).eq("value_id",params.get("valueId")).eq("type_id",params.get("typeId"))
        );
        String handleType = "add";
        if (StringUtil.isNullOrEmpty(collectEntities) || collectEntities.size() < 1) {
            CollectVo collectEntity = new CollectVo();
            collectEntity.setAddTime(System.currentTimeMillis() / 1000);
            collectEntity.setTypeId(Integer.parseInt(params.get("typeId").toString()));
            collectEntity.setValueId(Integer.parseInt(params.get("valueId").toString()));
            collectEntity.setIsAttention(0);
            collectEntity.setUserId(userVo.getUserId());
            //添加收藏
            apiCollectService.save(collectEntity);
        } else {
            //取消收藏
            handleType = "delete";
            apiCollectService.removeById(collectEntities.get(0).getId());
        }
        return R.ok().put("type",handleType);
    }
}
